<template>
  <div class="page">
    <!-- 操作栏 -->
    <div class="header">
      <span>Image</span>
      <div class="flex items-center">
        <div v-if="isEdit" class="flex items-center">
          <el-tooltip effect="dark" content="Download" placement="top">
            <DownloadIcon class="mr-[16px] cursor_poi" @click="downImg" />
          </el-tooltip>
          <el-tooltip effect="dark" content="Delete" placement="top">
            <DeleteIcon class="mr-[24px] cursor_poi" @click="batchDeleteImg" />
          </el-tooltip>

          <CloseIcon />
        </div>
        <span @click="editChange" class="cursor_poi line ml-[2px]" v-slide-underline>
          {{ isEdit ? 'Deselect' : 'Bulk Edit' }}
        </span>
      </div>
    </div>
    <!-- 内容区组件 -->
    <div
      class="right"
      v-infinite-scroll="loadMore"
      :infinite-scroll-disabled="loading || !hasMore"
      :infinite-scroll-immediate="false">
      <!-- 按天分组显示 -->
      <div v-for="group in groupedResults" :key="group.dateKey">
        <!-- 日期标题 - 直接显示YYYY-MM-DD格式 -->
        <div class="date-title">{{ group.dateKey }}</div>

        <!-- 图片容器 - 使用flex布局自动换行 -->
        <div class="image-container">
          <div v-for="img in group.images" :key="img.img_id" class="img-item">
            <div class="img-view">
              <img
                :src="img.img_url"
                alt="Generated image"
                class="preview-image"
                @click="goDetail(img)" />
              <!-- 批量编辑按钮 -->
              <div class="edit_btns" v-if="isEdit" @click="selectImg(img)">
                <CheckedIcon v-if="img.isCheck" />
                <CheckIcon v-else />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载状态提示 -->
      <div v-if="loading" class="loading">loading...</div>
      <div v-else-if="!hasMore && genResults.length > 0" class="no-more">No more data</div>
      <div v-else-if="!loading && genResults.length === 0" class="no-data">No data</div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { AiAPI } from '@/api/ai';
  import { AIType, GenerateResultListVO, GenerateResultVO } from '@/types/ai';
  import { downloadImage, packImagesToZip } from '@/utils/tools';
  import { dayjs, ElMessageBox } from 'element-plus';
  import { onMounted, ref, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import CloseIcon from '../icons/CloseIcon.vue';
  import CheckedIcon from '../icons/CheckedIcon.vue';
  import CheckIcon from '../icons/CheckIcon.vue';
  import DownloadIcon from '@/components/icons/ai/DownloadIcon.vue';
  import DeleteIcon from '@/components/icons/ai/DeleteIcon.vue';

  const genResults = ref<GenerateResultVO[]>([]);
  const start = ref(0); // 当前分页位置
  const hasMore = ref(true); // 是否有更多数据
  const loading = ref(false); // 加载状态
  const pageSize = 10; // 每页数据量

  const isEdit = ref<Boolean>(false);
  const router = useRouter();

  const editChange = () => {
    // 如果当前是编辑模式，在切换前清除所有选中状态
    if (isEdit.value) {
      // 清除genResults中所有图片的选中状态
      genResults.value.forEach((item: any) => {
        item.result_imgs.forEach((img: any) => {
          img.isCheck = false;
        });
      });
    }

    isEdit.value = !isEdit.value;
  };

  // 切换选中状态
  const selectImg = (selectItem: any) => {
    // 使用Vue.set或通过替换整个对象来确保响应式更新
    genResults.value.forEach((item: any, itemIndex: number) => {
      item.result_imgs.forEach((img: any, imgIndex: number) => {
        if (selectItem?.img_id === img.img_id) {
          img.isCheck = !img.isCheck;
        }
      });
    });
  };

  // 批量下载图片
  const downImg = () => {
    const list: any = [];
    groupedResults.value.forEach((item: any) => {
      item.images.forEach((img: any) => {
        img.isCheck && list.push(img.img_id);
      });
    });
    if (list.length === 0) return;
    list.length === 1 ? downloadImage(list[0]) : packImagesToZip(list);
  };

  // 批量删除选中图片
  const batchDeleteImg = async () => {
    const list: any = [];
    groupedResults.value.forEach((item: any) => {
      item.images.forEach((img: any) => {
        img.isCheck && list.push(img);
      });
    });
    if (list.length === 0) return;
    try {
      // 显示确认对话框
      await ElMessageBox.confirm(
        'Deleting this image will remove it permanently and clear all drawn masks',
        'Delete this image?',
        {
          confirmButtonText: 'Delete',
          cancelButtonText: 'Cancel',
          center: true,
          showClose: false,
          customClass: 'delete-confirm-dialog',
        }
      );

      const tasks = list.map((item: any) => ({
        task_id: item.task_id,
        img_ids: [item.img_id],
      }));

      await AiAPI.deleteGenerateImg({ tasks });

      isEdit.value = false;
      getGenerateResult();
    } catch {}
  };

  // 跳转图片详情
  const goDetail = (item: any) => {
    // 确保在编辑模式下不执行跳转
    if (!isEdit.value) {
      // 根据item数据结构，使用router.push跳转到详情页并传递task_id参数
      router.push({
        path: '/generator/detail',
        query: {
          task_id: item.task_id,
        },
      });
    }
  };

  // 按天分组后的数据（有序）
  const groupedResults = computed(() => {
    const groups: Record<string, Array<any>> = {};

    genResults.value.forEach((item: any) => {
      if (item?.result_imgs?.length) {
        // 使用dayjs格式化日期为YYYY-MM-DD格式，用作分组键
        const dateKey = formatDate(item.created_at);

        if (!groups[dateKey]) {
          groups[dateKey] = [];
        }

        // 将图片添加到对应的日期分组
        item.result_imgs.forEach((img: any) => {
          groups[dateKey].push({
            img_id: img.img_id,
            img_url: img.img_url,
            prompt_text: item.prompt_text,
            task_id: item.task_id,
            isCheck: img.isCheck,
          });
        });
      }
    });

    // 获取所有日期键并按降序排序（最新日期在前）
    const sortedDateKeys = Object.keys(groups).sort((a, b) => {
      return dayjs(b).valueOf() - dayjs(a).valueOf();
    });

    // 返回有序的数组结构
    return sortedDateKeys.map((dateKey) => ({
      dateKey,
      images: groups[dateKey],
    }));
  });

  // 初始化加载数据
  onMounted(() => {
    getGenerateResult();
  });

  // 获取初始数据
  const getGenerateResult = async () => {
    loading.value = true;
    try {
      const params = {
        gen_type: AIType.ALL,
        start: 0,
        size: pageSize,
      };

      const res = await AiAPI.generateTaskHistory(params);
      const data: GenerateResultListVO = res?.data || {};
      const list = data?.results || [];

      // 替换数据
      genResults.value = list;

      // 更新分页状态
      start.value = data?.next_start || 0;
      hasMore.value = data?.has_more || false;
    } catch (error) {
      console.error('获取AI生成历史失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 加载更多数据
  const loadMore = async () => {
    // 如果已经没有更多数据或正在加载，则不再请求
    if (!hasMore.value || loading.value) {
      return;
    }

    loading.value = true;
    try {
      const params = {
        gen_type: AIType.ALL,
        start: start.value,
        size: pageSize,
      };

      const res = await AiAPI.generateTaskHistory(params);
      const data: GenerateResultListVO = res?.data || {};
      const list = data?.results || [];

      // 追加数据
      genResults.value = [...genResults.value, ...list];

      // 更新分页状态
      start.value = data?.next_start || 0;
      hasMore.value = data?.has_more || false;
    } catch (error) {
      console.error('加载更多AI生成历史失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 使用dayjs格式化日期为YYYY-MM-DD格式
  const formatDate = (dateString: string): string => {
    return dayjs(dateString).format('YYYY-MM-DD');
  };
</script>

<style lang="scss" scoped>
  @use '@/styles/variables' as *;
  @use '@/styles/mixins' as *;
  .page {
    // display: flex;
    padding: 0 20px;
  }
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 64px;
    color: #222;

    font-weight: 600;
    font-style: SemiBold;
    font-size: 16px;
    line-height: 100%;
    letter-spacing: 0%;
    text-align: right;
  }
  .right {
    overflow-y: auto;
    height: calc(100vh - 128px);
    scrollbar-width: none;
  }

  .edit_btns {
    position: absolute;
    right: 4px;
    top: 4px;
    z-index: 9;
  }
  // 日期标题样式
  .date-title {
    display: inline-block;

    font-weight: 500;
    font-style: Medium;
    font-size: 14px;
    line-height: 100%;
    letter-spacing: 0%;
    color: #333;
    padding: 8px 12px;
    background: #ededed;
    color: #222222;
    border-radius: 8px;
    margin-bottom: 8px;
  }

  // 图片容器 - flex布局自动换行
  .image-container {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 32px;
    .img-item {
      position: relative;
      // 为图片容器添加相对定位，并在hover时显示遮罩层
      .img-view {
        position: relative;
        display: inline-block;
      }

      // 遮罩层样式
      .img-view::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: transparent;
        border-radius: 8px;
        transition: background-color 0.3s ease;
        pointer-events: none;
      }

      // hover时显示透明黑色遮罩层
      .img-view:hover::after {
        background-color: rgba(0, 0, 0, 0.15);
      }

      // 预览图片样式
      .preview-image {
        width: 212px;
        aspect-ratio: 1;
        object-fit: cover;
        border-radius: 8px;
        cursor: pointer;
      }
    }
  }

  .loading,
  .no-more,
  .no-data {
    text-align: center;
    padding: 20px 0;
    color: #999;
    font-size: 14px;
  }

  .line {
    display: inline-block;
    background-image: linear-gradient(to right, #cbcbcb, #cbcbcb);
    background-size: 100% 1px;
    background-position: bottom;
    background-repeat: no-repeat;
  }
</style>
